package cn.fl.institution.controller;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstNpBscInfoService;
import cn.fl.customer.vo.CstNpBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.condition.PrjCstAccInfoQueryCondition;
import cn.fl.project.service.IPrjCstAccInfoService;
import cn.fl.project.vo.PrjCstAccInfoVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import pay.business.facade.custpay.api.IBankCardApiService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 项目基础信息表 控制层 建设银行
 */
@Controller
@RequestMapping("/institution/ccbank")
public class PrjBscInfoInsCcbankController {

    /**
     * 自然人信息
     */
    @Autowired
    private ICstNpBscInfoService cstNpBscInfoService;

    /**
     * 项目客户基础信息表
     */
    @Autowired
    private IPrjCstAccInfoService prjCstAccInfoService;

    /**
     * 银行卡服务
     */
    @Autowired
    private IBankCardApiService bankCardApiService;

    /**
     * 保存 项目客户信息
     */
    @RequestMapping(value = "/saveForCcbank.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO saveForCcbank(HttpServletRequest request) throws BaseException {
        BaseLogUtils.newLogger("saveForCcbank.修改项目客户账户信息：" + JSON.toJSONString(request.getParameterMap()) + "，操作人：" + CurrentThreadContext.getCurrentUserName()).info();
        //项目客户信息表id
        String cstAccInfoId = request.getParameter("cstAccInfoId");
        //机构code
        String insCode = request.getParameter("insCode");
        //项目id
        String prjId = request.getParameter("prjId");
        //客户id
        String cstId = request.getParameter("cstId");
        //客户姓名
        String cstNm = request.getParameter("cstNm");
        //银行账号
        String accNo = request.getParameter("accNo");
        //手机号
        String mp = request.getParameter("mp");
        //月收入
        String monthInc = request.getParameter("monthInc");
        //身份证号
        String certNo = request.getParameter("certNo");
        //银行代码
        String bkCd = request.getParameter("bkCd");
        //银行名称
        String bkNm = request.getParameter("bkNm");

        DataResultVO dataResultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, "保存成功");
        try {
            if (StringUtils.isEmpty(prjId)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目id为空!");
            }
            if (StringUtils.isEmpty(cstId)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户id为空!");
            }
            if (StringUtils.isEmpty(cstNm)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户名称为空!");
            }
            if (StringUtils.isEmpty(bkNm) || StringUtils.isEmpty(bkCd)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "开户银行为空!");
            }
            if (StringUtils.isEmpty(monthInc)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护月收入!");
            }
            if (StringUtils.isEmpty(accNo)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护银行卡号!");
            }
            if (StringUtils.isEmpty(mp)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护银行预留手机号!");
            }
            // 修改自然人月收入
            CstNpBscInfoVO bscInfoVO = this.cstNpBscInfoService.selectById(Long.valueOf(cstId));
            CstNpBscInfoVO cstNpBscInfoVO = new CstNpBscInfoVO();
            if (null != bscInfoVO) {
                boolean flag = false;
                cstNpBscInfoVO.setId(bscInfoVO.getId());
                // 月收入转为分
                Long mrIncMoney = DecimalUtils.convertYuanToFen(Double.valueOf(monthInc));
                // 月收入转换年收入
                Double yrInc = DecimalUtils.mul(mrIncMoney.doubleValue(), 12d);
                if (!Objects.equals(bscInfoVO.getYrInc().doubleValue(), yrInc)) {
                    cstNpBscInfoVO.setYrInc(yrInc.longValue());
                    flag = true;
                }
                if (flag) {
                    cstNpBscInfoVO.setMdfTm(new Date());
                    cstNpBscInfoVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
                }
                BaseLogUtils.newLogger("saveForCcbank.修改自然人信息cstNpBscInfoVO" + JSON.toJSONString(cstNpBscInfoVO)).info();
                boolean modify = this.cstNpBscInfoService.modify(cstNpBscInfoVO);
                BaseLogUtils.newLogger("saveForCcbank.修改自然人信息modify=" + modify).info();
            }

            // 修改项目客户信息
            PrjCstAccInfoQueryCondition condition = new PrjCstAccInfoQueryCondition();
            if (StringUtils.isNotEmpty(cstAccInfoId)) {
                condition.setId(Long.valueOf(cstAccInfoId));
            }

            //校验银行卡号是否为建设银行卡号
            Boolean chkBinFlag = true;
            String chkBinCd = BaseConstant.IS_YESNO_NO_STR;
            String chkBinCdDesc = "";
            PrjCstAccInfoQueryCondition prjCstAccInfoQC = new PrjCstAccInfoQueryCondition();
            prjCstAccInfoQC.setPrjId(Long.valueOf(prjId));
            prjCstAccInfoQC.setIsDel(BaseConstant.IS_YESNO_NO);
            prjCstAccInfoQC.setInsCode(insCode);
            BaseLogUtils.newLogger("saveForCcbank.根据prjId获取账户信息prjId=" + prjId).info();
            List<PrjCstAccInfoVO> prjCstAccInfoVOS = this.prjCstAccInfoService.searchList(prjCstAccInfoQC);
            BaseLogUtils.newLogger("saveForCcbank.根据prjId获取账户信息prjCstAccInfoVOS=" + JSON.toJSONString(prjCstAccInfoVOS)).info();
            if (CollectionUtils.isNotEmpty(prjCstAccInfoVOS)) {
                PrjCstAccInfoVO prjCstAccInfoVO = prjCstAccInfoVOS.get(0);
                //说明该项目已存在账户信息 则跟据id进行修改
                if (condition.getId() == null) {
                    condition.setId(prjCstAccInfoVO.getId());
                }
                if (accNo.equals(prjCstAccInfoVO.getAccNo()) && BaseConstant.IS_YESNO_YES_STR.equals(prjCstAccInfoVO.getChkBinCd())) {
                    //银行卡号没有变动且已校验通过，不用校验银行卡号
                    chkBinFlag = false;
                }
            }
            if (chkBinFlag) {
                BaseLogUtils.newLogger("saveForCcbank.校验银行卡号START,accNo:" + accNo.trim()).info();
                DataResultDTO dataResultDTO = this.bankCardApiService.searchCardBin(accNo.trim());
                BaseLogUtils.newLogger("saveForCcbank.校验银行卡号END,accNo:" + accNo.trim() + ",dataResultDTO" + JSON.toJSONString(dataResultDTO)).info();
                if (dataResultDTO != null && dataResultDTO.getSuccess() == BaseConstant.IS_YESNO_YES) {
                    Object data = dataResultDTO.getData();
                    if (data != null) {
                        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(data));
                        String bankCd = jsonObject.getString("bankCd");
                        if ("CCB".equals(bankCd)) {
                            chkBinCd = BaseConstant.IS_YESNO_YES_STR;
                        } else {
                            chkBinCdDesc = "银行账号有误，银行卡号需为建行卡号且为借记卡，请核实修改";
                        }
                    } else {
                        chkBinCdDesc = "校验银行卡号失败!";
                    }
                } else {
                    if (dataResultDTO != null && StringUtils.isNotEmpty(dataResultDTO.getInfo())) {
                        chkBinCdDesc = dataResultDTO.getInfo();
                    } else {
                        chkBinCdDesc = "校验银行卡号失败!";
                    }
                }
                //校验卡bin时才给该字段赋值
                condition.setChkBinCd(chkBinCd);
            }
            condition.setBkCd(bkCd);
            condition.setBkNm(bkNm);
            condition.setPrjId(Long.valueOf(prjId));
            condition.setCstId(Long.valueOf(cstId));
            condition.setInsCode(insCode);
            condition.setCstNm(cstNm);
            condition.setAccNo(accNo.trim());
            condition.setAccNm(cstNm);
            condition.setMp(mp);
            condition.setCertNo(certNo.trim());
            condition.setCertTypCd(DictionaryConstant.CODE_CERT_TYP_CD_0);
            BaseLogUtils.newLogger("saveForCcbank.修改项目客户账户信息,condition:" + JSONObject.toJSONString(condition)).info();
            dataResultVO = this.prjCstAccInfoService.modifyPrjAccInfo(condition);
            if (BaseConstant.IS_YESNO_YES == dataResultVO.getSuccess()) {
                //校验银行卡bin结果
                if (chkBinFlag && BaseConstant.IS_YESNO_NO_STR.equals(chkBinCd)) {
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                    dataResultVO.setInfo(chkBinCdDesc);
                    return dataResultVO;
                }
                Map<String, String> resultMap = (Map<String, String>) dataResultVO.getData();
                String chkRstCd = resultMap.get("chkRstCd");
                String rstDesc = resultMap.get("rstDesc");
                String bankCardType = resultMap.get("bankCardType");
                //四要素结果
                if (!BaseConstant.IS_YESNO_YES_STR.equals(chkRstCd)) {
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                    dataResultVO.setInfo(rstDesc);
                    return dataResultVO;
                }
                //银行卡类型
                if (!BaseConstant.IS_YESNO_NO_STR.equals(bankCardType)) {
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                    dataResultVO.setInfo("不支持此类银行卡，请更换为借记卡");
                    return dataResultVO;
                }
            }
        } catch (BaseException ex) {
            dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            dataResultVO.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("saveForCcbank.保存项目客户账户信息及校验,prjId:" + prjId + ".ERROR:" + ex.getMessage()).info();
        } catch (Exception e) {
            BaseLogUtils.newLogger("saveForCcbank.保存失败，系统异常" + e).info();
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "保存失败，系统异常");
        }
        BaseLogUtils.newLogger("saveForCcbank.保存项目客户账户信息及校验返回dataResultVO=" + JSON.toJSONString(dataResultVO)).info();
        return dataResultVO;
    }
}
